package com.tanhua.server.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.service.UserService;
import com.tanhua.server.utils.NoAuthorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作用：用于校验token，如果有效就将userId存入UserThreadLocal中，如果无效，响应401状态码
 */
@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        if (handlerMethod.hasMethodAnnotation(NoAuthorization.class)) {
            //该请求无需校验
            return true;
        }

        //获取到token
        String token = request.getHeader("Authorization");
        if (StrUtil.isNotEmpty(token)) {
            Long userId = this.userService.checkToken(token);
            if (null != userId) {
                //token有效
                UserThreadLocal.set(userId);
                return true;
            }
        }

        //响应状态码为401
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
